package com.zivwu.library.ui.image;


import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.zivwu.library.AppModule;
import com.zivwu.library.ann.PerActivity;
import com.zivwu.library.dao.local.cache.DiskLruCache;
import com.zivwu.library.utils.DiskLruCacheUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;

@Module(includes = AppModule.class)
@PerActivity
public class PhotoFileModule {
    private static final String AUTHORITY = "com.zivwu.fileprovider";
    private final String IMAGE_DIR = "images";

    @Provides
    @PerActivity
    @Named("imageFile")
    File providerImageFile(@Named("cacheFile") File file) {
        return new File(file, IMAGE_DIR);
    }

    @Named("imageFileName")
    @Provides
    File providerImageFileName(@Named("imageFile") File file)  {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        if (!file.exists()) {
            file.mkdirs();
        }
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    file      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    @Provides
    Uri providerImageUri(Context context, @Named("imageFileName") File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, AUTHORITY, file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    @Provides
    @PerActivity
    @Named("image")
    DiskLruCache providerImageDiskLruCache(@Named("imageFile") File file) {
        return DiskLruCacheUtil.open(file, 1, 1, 10 * 1024 * 1024);
    }

}
